<template>
  <PayV2 v-if="packages.length"
    :showPay="!this.vipUnlimited"
    :packages="packages"
    :pkgId="pkgId"
    :windowName="windowName"
    @paySuccess="onPaySuccess"/>
</template>
<script>
import { mapGetters } from 'vuex'
import PayV2 from '@/components/pay/index-v2.vue'
// import scenecouponMixin from '@/mixins/scene-coupon.js'
import { isPassVersionByApp, isPassVersion } from '@/utils/judge'
import { pkgByCid, getLeftDay } from '@/utils/costum'
import { getPackagesList } from '@/api/rights'
import { getChangeExperienceInfo } from '@/api/user'

export default {
  name: 'PayPage',
  components: {
    PayV2
  },
  // mixins: [scenecouponMixin],
  data () {
    return {
      packages: [],
      windowName: 'XZDesktopOrderVIP',
      vipUnlimited: false
    }
  },
  computed: {
    ...mapGetters(['appInfo', 'userInfo', 'hasLogin']),
    userPackageInfo () {
      const buyList = this.userInfo.buy_right_package || []
      const expList = this.expList
      for (const item of buyList) {
        const index = expList.findIndex(itemb => itemb.pkg_id === item.pkg_id)
        if (index !== -1) {
          const obj = expList.splice(index, 1)[0]
          Object.assign(item, obj)
        }
      }
      return buyList.concat(this.expList)
    }
  },
  watch: {
    'userInfo.user_id': {
      handler (val) {
        if (val) {
          this.buyCurrPackagesAuth()
        } else if (val !== -1000) {
          this.getExperienceInfo()
        }
      },
      immediate: true
    }
  },
  created () {
    const query = this.$route.query
    const app = query.app
    this.pkgId = query.pkgid || pkgByCid[app][0] || '10000'
    this.init()
    this.$xz('xz_set_window_size', this.windowName, 771, 596)
    this.$xzReg('inform_self_param', res => {
      this.toPageForParam(res)
    })
  },
  methods: {
    async init () {
      if (this.hasLogin) {
        await this.$store.dispatch('user/getUserInfo')
      }
      await this.getPackages()
      this.$xz('xz_page_load_finished', this.windowName)
    },
    toPageForParam (obj) {
      let data
      try {
        data = JSON.parse(obj)
      } catch (e) {
        data = null
      }
      if (!data) {
        try {
          obj = decodeURIComponent(obj)
          // 解决跨端通讯，字符串存在 / 被客户端截断问题
          data = JSON.parse(obj)
        } catch (e) {
          data = {}
        }
      }
      if (data.business === 'buyMember') {
        this.$eventBus.$emit('pay-v2-action', data)
      }
    },
    getExperienceInfo () {
      getChangeExperienceInfo({ pkg_id: this.appInfo.allPackages }).then(res => {
        const list = res.data.list || []
        this.expList = list.map(item => {
          item.id = item.p_id
          return item
        })
      })
    },
    /** 获取在售权益包 */
    async getPackages () {
      await getPackagesList({ pid: this.appInfo.allPackages })
        .then(res => {
          const list = this.filtersRights(res.data.list || [])
          this.transPackagesList(list)
        })
    },
    transPackagesList (list) {
      if (!list.length) return
      list.map(itemb => {
        const buyPackage = this.getBuyPackage(itemb)
        const leftDay = getLeftDay(buyPackage.expire_at, this.userInfo.server_time)
        const tag = this.getTag(buyPackage, leftDay)
        itemb.trial_status = buyPackage.trial_status
        itemb.tag = tag
        itemb.leftDay = leftDay
        itemb.expire_at = buyPackage.expire_at
        itemb.cat_list = (itemb.cat_list || []).map(item => {
          item.right_list = this.filtersRights(item.right_list)
          return item
        })
        if (buyPackage.trial_status !== 2) {
          itemb.trialTime = '7天'
        } else if (buyPackage.minutes > 0) {
          itemb.trialTime = buyPackage.minutes >= 1440 ? `${buyPackage.minutes / 24 / 60}天` : `${buyPackage.minutes}分钟`
        } else {
          itemb.trialTime = ''
        }

        itemb.showTrial = itemb.showTrial || false
        return itemb
      })
      this.packages = list
    },
    filtersRights (list = []) {
      return list.filter(item => {
        item.name = item.name.replace('\n', '')
        return isPassVersion(item.min_ver)
      })
    },
    getBuyPackage (pckItem) {
      if (!pckItem || !this.userPackageInfo) return {}
      const obj = this.userPackageInfo.find((item) => item.id === pckItem.id)
      return obj || {}
    },
    // tag类型 -2试用已到期 -1已到期 0 非会员 1试用过未到期 2已购买 3终身 4快到期
    getTag (buyPackage, leftDay) {
      if (!buyPackage.id || !buyPackage.expire_at) return 0
      if (buyPackage.unlimited) return 3
      if (leftDay <= 0) {
        if (!buyPackage.has_buy) {
          return -2
        } else {
          return -1
        }
      } else {
        if (!buyPackage.has_buy) {
          return 1
        } else if (leftDay < 8) {
          return 4
        } else {
          return 2
        }
      }
    },
    onPaySuccess () {
      this.$xz('xz_switch_dialog', this.windowName, false)
    },
    buyCurrPackagesAuth () {
      const buyList = this.userInfo.buy_right_package || []
      const { unlimited } = buyList.find(buyIt => buyIt.pkg_id === this.pkgId) || {}
      if (isPassVersionByApp({
        '22': { v: '3.3.0.14' },
        '111': { v: '3.2.10.0' }
      })) {
        this.vipUnlimited = unlimited
        return
      }
      if (unlimited) {
        const isOpenUserCenter = isPassVersion('3.2.0')
        this.$PsMessageBox({
          iconClass: 'error',
          message: `您已购买当前权益包终身会员，请选择其他权益包`,
          confirmButtonText: isOpenUserCenter ? '查看' : '确定',
          showCancelButton: isOpenUserCenter
        }).then((action) => {
          if (action === 'confirm' && isOpenUserCenter) {
            this.$xz('xz_switch_dialog', 'XZMainWindow', true)
            this.$xz('xz_switch_tab', 0)
          }
        }).finally(() => {
          this.$xz('xz_switch_dialog', this.windowName, false)
        })
      }
    }
  }
}
</script>
<style scoped lang="scss">
.pay-page{
  height: 100%;
  padding: 20px 0;
  background: #34353B;
  overflow: auto;
  overflow-y: scroll;
}
.pay-nav{
  height: 32px;
  border-bottom: 1px solid rgba(255,255,255,0.1);
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 80px;
}
.pay-nav_item{
  font-weight: bold;
  font-size: 14px;
  color: rgba(255, 255, 255, .7);
  position: relative;
  cursor: pointer;
  &:hover{
    color: rgba(255, 255, 255, 1);
  }
  &.on{
    color: #F8DE9D;
    &::before {
      opacity: 1;
      width: 38px;
    }
  }
  &::before {
    content: '';
    position: absolute;
    bottom: -8px;
    left: 50%;
    transform: translateX(-50%);
    width: 0;
    height: 3px;
    background: #F8DE9D;
    border-radius: 10px;
    opacity: 0;
    transition: all .1s ease;
  }
  .svg-icon{
    font-size: 18px;
    margin-right: 6px;
  }
}

.pay-com{
  padding: 0 14px 0 20px;
}
</style>
